<!-- V-webapp/src/views/CheckoutView.vue -->
<template>
  <div class="checkout-container">
    <!-- 调试信息（开发时显示） -->
    <div v-if="isDevelopment" style="background: #e6f7ff; padding: 10px; margin-bottom: 10px; border-radius: 8px;">
      <p style="margin: 0; font-size: 12px; color: #1890ff;">
        <strong>调试信息:</strong> 选中 {{ selectedItems.length }} 件商品，购物车ID: {{ selectedItems.map(item => item.cart_id || item.id) }}
      </p>
    </div>

    <div class="page-header">
      <el-button @click="$router.back()" class="back-btn" type="primary" link>
        <el-icon><ArrowLeft /></el-icon>
      </el-button>
      <h2>订单确认</h2>
    </div>
    
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="5" animated />
    </div>

    <div v-else-if="!selectedItems || selectedItems.length === 0" class="empty-container">
      <el-empty description="请选择要购买的商品">
        <el-button type="primary" @click="$router.push('/cart')">
          返回购物车
        </el-button>
      </el-empty>
    </div>

    <div v-else class="checkout-content">
      <!-- 收货地址 -->
      <div class="section-card">
        <h3 class="section-title">收货信息</h3>
        <el-form :model="shippingForm" :rules="shippingRules" ref="shippingFormRef">
          <el-form-item label="收货人姓名" prop="recipient_name">
            <el-input 
              v-model="shippingForm.recipient_name" 
              placeholder="请输入收货人姓名"
              maxlength="20"
            />
          </el-form-item>
          
          <el-form-item label="联系电话" prop="recipient_phone">
            <el-input 
              v-model="shippingForm.recipient_phone" 
              placeholder="请输入联系电话"
              maxlength="11"
            />
          </el-form-item>
          
          <el-form-item label="收货地址" prop="shipping_address">
            <el-input 
              v-model="shippingForm.shipping_address" 
              type="textarea"
              :rows="2"
              placeholder="请输入详细收货地址"
              maxlength="200"
              show-word-limit
            />
          </el-form-item>
          
          <el-form-item label="备注信息" prop="note">
            <el-input 
              v-model="shippingForm.note" 
              type="textarea"
              :rows="2"
              placeholder="选填：订单备注信息"
              maxlength="200"
              show-word-limit
            />
          </el-form-item>
        </el-form>
      </div>

      <!-- 商品信息 -->
      <div class="section-card">
        <h3 class="section-title">商品信息</h3>
        <div class="product-list">
          <div 
            v-for="item in selectedItems" 
            :key="item.id"
            class="product-item"
          >
            <el-image 
              :src="getProductImage(item.product)" 
              class="product-image"
              fit="cover"
            >
              <template #error>
                <div class="image-error">
                  <el-icon><Picture /></el-icon>
                </div>
              </template>
            </el-image>
            
            <div class="product-info">
              <h4 class="product-name">{{ getProductName(item.product) }}</h4>
              <p class="product-desc">{{ getProductDescription(item.product) }}</p>
              <div class="product-price-quantity">
                <span class="price">¥{{ item.product.price }}</span>
                <span class="quantity">x{{ item.quantity }}</span>
              </div>
            </div>
            
            <div class="product-subtotal">
              ¥{{ (item.product.price * item.quantity).toFixed(2) }}
            </div>
          </div>
        </div>
      </div>

      <!-- 价格汇总 -->
      <div class="section-card">
        <h3 class="section-title">价格汇总</h3>
        <div class="price-summary">
          <div class="price-row">
            <span>商品总价</span>
            <span>¥{{ totalAmount.toFixed(2) }}</span>
          </div>
          <div class="price-row">
            <span>运费</span>
            <span>¥0.00</span>
          </div>
          <div class="price-row total">
            <span>实付金额</span>
            <span class="final-amount">¥{{ totalAmount.toFixed(2) }}</span>
          </div>
        </div>
      </div>

      <!-- 底部支付栏 -->
      <div class="checkout-bar">
        <div class="checkout-left">
          <div class="total-amount">
            合计: <span class="amount">¥{{ totalAmount.toFixed(2) }}</span>
          </div>
        </div>
        <div class="checkout-right">
          <el-button 
            type="primary" 
            class="pay-btn"
            :loading="submitting"
            @click="handleCreateOrder"
          >
            {{ submitting ? '创建订单中...' : `立即支付` }}
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowLeft, Picture } from '@element-plus/icons-vue'
import { createOrder } from '@/api/orders'
import type { CartItem } from '@/api/cart'

const router = useRouter()
const route = useRoute()
const loading = ref(false)
const submitting = ref(false)
const shippingFormRef = ref()

// 开发环境判断
const isDevelopment = ref(import.meta.env.MODE === 'development')

// 选中的商品
const selectedItems = ref<CartItem[]>([])

// 收货表单
const shippingForm = ref({
  recipient_name: '',
  recipient_phone: '',
  shipping_address: '',
  note: ''
})

// 表单验证规则
const shippingRules = {
  recipient_name: [
    { required: true, message: '请输入收货人姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '姓名长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  recipient_phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  shipping_address: [
    { required: true, message: '请输入收货地址', trigger: 'blur' },
    { min: 5, max: 200, message: '地址长度在 5 到 200 个字符', trigger: 'blur' }
  ]
}

// 计算总金额
const totalAmount = computed(() => {
  return selectedItems.value.reduce((total, item) => {
    return total + (item.product.price * item.quantity)
  }, 0)
})

// 获取商品图片
const getProductImage = (product: CartItem['product']) => {
  if (product.cover_image) {
    // 这里可以根据实际情况处理图片URL
    return product.cover_image
  }
  if (product.product_images && product.product_images.length > 0) {
    return product.product_images[0].image_url
  }
  return ''
}

// 获取商品名称
const getProductName = (product: CartItem['product']) => {
  return product.name || product.product_name || '未知商品'
}

// 获取商品描述
const getProductDescription = (product: CartItem['product']) => {
  return product.description || '暂无描述'
}

// 加载选中的商品 - 修复数据加载逻辑
const loadSelectedItems = async () => {
  try {
    loading.value = true
    console.log('🛒 路由参数:', route.query)
    
    // 方法1：从本地存储获取结算商品数据（优先）
    const checkoutItems = localStorage.getItem('checkoutItems')
    if (checkoutItems) {
      selectedItems.value = JSON.parse(checkoutItems)
      console.log('✅ 从本地存储加载结算商品:', selectedItems.value)
      return
    }
    
    // 方法2：从路由参数获取（备用方案）
    const itemIds = route.query.items as string
    if (itemIds) {
      console.log('🔄 从路由参数获取商品ID:', itemIds)
      
      // 从本地存储获取完整的购物车数据
      const cartData = localStorage.getItem('cartData')
      if (cartData) {
        const cartItems: CartItem[] = JSON.parse(cartData)
        const selectedIds = itemIds.split(',').map(id => parseInt(id))
        
        selectedItems.value = cartItems.filter(item => 
          selectedIds.includes(item.id)
        )
        console.log('✅ 从本地存储加载选中的商品:', selectedItems.value)
      } else {
        console.log('❌ 购物车数据不存在')
        // 如果没有购物车数据，使用模拟数据
        selectedItems.value = [
          {
            id: 1,
            cart_id: 1,
            product_id: 1,
            quantity: 2,
            selected: true,
            product: {
              id: 1,
              name: '测试商品',
              description: '这是一个测试商品',
              price: 99.99,
              stock: 10,
              cover_image: ''
            }
          }
        ] as CartItem[]
      }
    }
    
    console.log('📦 最终选中的商品:', selectedItems.value)
    
  } catch (error) {
    console.error('❌ 加载选中商品失败:', error)
    ElMessage.error('加载商品信息失败')
  } finally {
    loading.value = false
  }
}

// 创建订单 - 修复错误处理
const handleCreateOrder = async () => {
  try {
    // 先手动检查必填字段
    if (!shippingForm.value.recipient_name?.trim()) {
      ElMessage.error('请输入收货人姓名')
      return
    }
    
    if (!shippingForm.value.recipient_phone?.trim()) {
      ElMessage.error('请输入联系电话')
      return
    }
    
    if (!shippingForm.value.shipping_address?.trim()) {
      ElMessage.error('请输入收货地址')
      return
    }
    
    // 验证手机号格式
    const phoneRegex = /^1[3-9]\d{9}$/
    if (!phoneRegex.test(shippingForm.value.recipient_phone)) {
      ElMessage.error('请输入正确的手机号码')
      return
    }

    console.log('✅ 表单验证通过')
    submitting.value = true

    // 确保有选中的商品
    if (!selectedItems.value || selectedItems.value.length === 0) {
      ElMessage.error('没有选中的商品，请返回购物车重新选择')
      return
    }

    // 准备订单数据
    const cartIds = selectedItems.value.map(item => item.cart_id || item.id)
    console.log('📦 使用的购物车ID:', cartIds)

    const orderData = {
      shipping_address: shippingForm.value.shipping_address,
      recipient_name: shippingForm.value.recipient_name,
      recipient_phone: shippingForm.value.recipient_phone,
      note: shippingForm.value.note || '',
      cart_ids: cartIds
    }

    console.log('📦 创建订单数据:', orderData)

    // 调用创建订单API
    const response = await createOrder(orderData)
    console.log('✅ 订单创建响应:', response)

    if (response.success || response.code === 200 || response.code === 201) {
      ElMessage.success('订单创建成功！')
      
      // 清除本地存储的结算商品数据
      localStorage.removeItem('checkoutItems')
      
      // 跳转到支付页面
      const orderData = response.data || response
      const orderId = orderData.order_id || orderData.id
      const orderNumber = orderData.order_number
      
      if (!orderId) {
        throw new Error('订单ID不存在')
      }
      
      router.push({
        path: '/payment',
        query: { 
          order_id: orderId,
          order_number: orderNumber
        }
      })
    } else {
      throw new Error(response.message || '创建订单失败')
    }

  } catch (error: any) {
    console.error('❌ 创建订单失败:', error)
    
    // 错误处理逻辑保持不变
    let errorMessage = '创建订单失败'
    
    if (error.response?.data) {
      const errorData = error.response.data
      console.log('🔍 错误响应数据:', errorData)
      
      if (errorData.message) {
        errorMessage = errorData.message
      }
    } else if (error.message) {
      errorMessage = error.message
    }
    
    ElMessage.error(errorMessage)
  } finally {
    submitting.value = false
  }
}

onMounted(() => {
  console.log('📱 订单确认页面加载')
  loadSelectedItems()
})
</script>

<style scoped>
.checkout-container {
  min-height: 100vh;
  background: #f5f5f5;
  padding: 16px;
  padding-bottom: 80px;
}

.page-header {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.loading-container,
.empty-container {
  padding: 40px 0;
  text-align: center;
}

.section-card {
  background: white;
  border-radius: 12px;
  padding: 16px;
  margin-bottom: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.section-title {
  margin: 0 0 16px 0;
  font-size: 16px;
  font-weight: 600;
  color: #333;
  padding-bottom: 8px;
  border-bottom: 1px solid #f0f0f0;
}

.product-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.product-item {
  display: flex;
  gap: 12px;
  align-items: center;
  padding: 8px 0;
}

.product-image {
  width: 60px;
  height: 60px;
  border-radius: 8px;
  flex-shrink: 0;
}

.image-error {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f5f5;
  border-radius: 8px;
  color: #999;
}

.product-info {
  flex: 1;
}

.product-name {
  margin: 0 0 4px 0;
  font-size: 14px;
  font-weight: 600;
  color: #333;
}

.product-desc {
  margin: 0 0 4px 0;
  font-size: 12px;
  color: #999;
}

.product-price-quantity {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.price {
  font-size: 14px;
  font-weight: 600;
  color: #ff4757;
}

.quantity {
  font-size: 12px;
  color: #666;
}

.product-subtotal {
  font-size: 16px;
  font-weight: 700;
  color: #ff4757;
  min-width: 80px;
  text-align: right;
}

.price-summary {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.price-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 14px;
  color: #666;
}

.price-row.total {
  padding-top: 8px;
  border-top: 1px solid #f0f0f0;
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.final-amount {
  font-size: 18px;
  color: #ff4757;
}

.checkout-bar {
  position: fixed;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  background: white;
  padding: 12px 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
  border-radius: 12px 12px 0 0;
  width: 100%;
  max-width: 480px;
  box-sizing: border-box;
  z-index: 1000;
}

.checkout-left {
  display: flex;
  align-items: center;
  flex-shrink: 0;
}

.checkout-left .total-amount {
  font-size: 16px;
  color: #333;
}

.amount {
  font-size: 20px;
  font-weight: 700;
  color: #ff4757;
}

.checkout-right {
  display: flex;
  align-items: center;
  flex-shrink: 0;
}

.pay-btn {
  padding: 12px 24px;
  border-radius: 20px;
  font-weight: 600;
  font-size: 16px;
  min-width: 120px;
}

/* 响应式设计 */
@media (max-width: 480px) {
  .checkout-bar {
    max-width: 100%;
    border-radius: 0;
  }
}
</style>